package com.rati.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rati.usercenter.model.domain.User;
import com.rati.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 缓存预热定时任务
 *
 * @author Lwh
 * @time 2022/12/22 22:00
 */
@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private final List<Long> mainUserList = Collections.singletonList(1L);

    @Scheduled(cron = "30 59 22 * * *")
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock("usercenter:PreCacheJob:doCache:lock");
        try {
            if (lock.tryLock(0, -1, TimeUnit.SECONDS)) {
                for (Long userId : mainUserList) {
                    QueryWrapper<User> wrapper = new QueryWrapper<>();
                    Page<User> page = userService.page(new Page<>(1, 20), wrapper);
                    String redisKey = String.format("usercenter:user:recommend:%s", userId);
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                    try {
                        valueOperations.set(redisKey, page, 30, TimeUnit.SECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error", e);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

}
